package org.jmqtt.broker.remoting.session;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import org.jmqtt.broker.remoting.util.RemotingHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 客户端连接管理器
 */
public class ConnectManager {

    private  Map<String /* clientId */, ClientSession /* ClientSession */> clientCache = new ConcurrentHashMap<>();

    private static final  ConnectManager INSTANCE  =  new ConnectManager();

    private ConnectManager(){}

    public static  ConnectManager getInstance(){
        return INSTANCE;
    }

    public ClientSession getClient(String clientId){
        return this.clientCache.get(clientId);
    }

    public ClientSession putClient(String clientId,ClientSession clientSession){
        return this.clientCache.put(clientId,clientSession);
    }

    public boolean containClient(String clientId){
        return this.clientCache.containsKey(clientId);
    }

    public ClientSession removeClient(String clientId){
        if (clientId != null) {
            return this.clientCache.remove(clientId);
        }
        return null;
    }

    /**
     * 返回客户端列表
     *
     * @return @return {@link List<JSONObject> }
     */
    public List<JSONObject> listClients() {
        List<JSONObject> resultList = new ArrayList<JSONObject>();
        clientCache.forEach((k, v) -> {
            ChannelHandlerContext ctx = v.getCtx();
            resultList.add(
                    new JSONObject() {{
                        put("clientId", k);
                        put("clientIp", RemotingHelper.getRemoteAddr(ctx.channel()));
                        put("initConnectDate", v.getInitConnectDate());
                        put("lossConnectTime", v.getLossConnectTime());
                    }}
            );
        });
        return resultList;
    }

}
